//
//  ChatMessageManageViewController.m
//  Btpin
//
//  Created by Vic on 2020/3/22.
//  Copyright © 2020 Vic. All rights reserved.
//

#import "ChatMessageManageViewController.h"
#import "ChatMessageManageCell.h"
#import "ChatMessageEditViewController.h"
#import "ChatSentenceModel.h"

@interface ChatMessageManageViewController ()<UITableViewDelegate, UITableViewDataSource, ChatMessageManageCellDelegate>
{
//    NSMutableArray *dataArray;
    
    UITableView *cTableView;
    UIButton *okBtn;
    UIButton *addBtn;
    
    NSInteger deleteRow;
    BOOL recordSort; // YES:在编辑排序 NO：没排序
}
@end

@implementation ChatMessageManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    dataArray = [NSMutableArray arrayWithCapacity:0];
    recordSort = YES;
    
    [self initUI];
    [self loadData];
}
- (void)loadData {
    SVPHUDShow;
    self.noDataView.hidden = YES;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    
    [BaseNetManager requestWithMethod:POST path:Chat_GetSentence_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            if ([data isKindOfClass:[NSArray class]]) {
                self->okBtn.hidden = NO;
//                if (self->dataArray && self->dataArray.count) {
//                    [self->dataArray removeAllObjects];
//                }
                if ([DataToolsControl sharedManager].chatSentenceArray && [DataToolsControl sharedManager].chatSentenceArray.count) {
                    [[DataToolsControl sharedManager].chatSentenceArray removeAllObjects];
                }
                for (NSDictionary *dic in data) {
                    ChatSentenceModel *model = [[ChatSentenceModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
//                    [self->dataArray addObject:model];
                    [[DataToolsControl sharedManager].chatSentenceArray addObject:model];
                }
                [self->cTableView reloadData];
            }
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
//        SVPHUDError(NetErrorAlertText);
        SVPHUDDismiss;
        [self.noDataView vcNilStatusType:VCNilStatusTypeOfNoNet superView:self.view];
    }];
}
- (void)initUI {
    self.navigationItem.title = @"常用语";
    
    cTableView = [UIToolsControl initTableViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-ScalePS(60)) target:self style:UITableViewStylePlain];
    cTableView.rowHeight = ScalePS(60);
    cTableView.tableFooterView = [[UIView alloc] init];
    cTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.view addSubview:cTableView];
    
    okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(0, 0, 50, 44) imageName:nil target:self action:@selector(okBtnTap) title:@"排序" titleColor:THEMECOLOR_OF_TEXT_333333];
    okBtn.titleLabel.font = Font(Font_15);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:okBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    okBtn.selected = NO;
    okBtn.hidden = YES;
    
    addBtn = [UIToolsControl initButtonWithFrame:CGRectMake(ScalePS(60), EndY(cTableView)+ScalePS(10), WIDTH-ScalePS(120), ScalePS(40)) imageName:nil target:self action:@selector(addBtnTap) title:@"添加常用语" titleColor:COLOR_OF_WHITE];
    addBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    addBtn.layer.cornerRadius = ScalePS(8);
    addBtn.layer.masksToBounds = YES;
    addBtn.titleLabel.font = Font(Font_15);
    [self.view addSubview:addBtn];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return dataArray.count;
    return [DataToolsControl sharedManager].chatSentenceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    ChatMessageManageCell *cell = [tableView dequeueReusableCellWithIdentifier:isCellID];
//    if (!cell) {
//        cell = [[ChatMessageManageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:isCellID];
//        cell.delegate = self;
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    }
//
////    ChatSentenceModel *model = dataArray[indexPath.row];
//    ChatSentenceModel *model = [DataToolsControl sharedManager].chatSentenceArray[indexPath.row];
//    [cell reloadDataForModel:model indexPath:indexPath];
//
//    return cell;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:isCellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:isCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = Font(Font_15);
        cell.textLabel.textColor = THEMECOLOR_OF_TEXT_333333;
        cell.textLabel.numberOfLines = 0;
    }
    
    ChatSentenceModel *model = [DataToolsControl sharedManager].chatSentenceArray[indexPath.row];
    cell.textLabel.text = model.text;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatSentenceModel *model = [DataToolsControl sharedManager].chatSentenceArray[indexPath.row];
    CGFloat height = [UIToolsControl textHeight:model.text size:CGSizeMake(WIDTH-50, MAXFLOAT) font:Font_15]+35;
    return height;
}
- (void)chatMessageManageCellEditTap:(NSIndexPath *)indexPath {
    ChatMessageEditViewController *CMEVC = [[ChatMessageEditViewController alloc] init];
//    ChatSentenceModel *model = dataArray[indexPath.row];
    ChatSentenceModel *model = [DataToolsControl sharedManager].chatSentenceArray[indexPath.row];
    CMEVC.editModel = [model copy];
    __weak typeof(self) weakSelf = self;
    CMEVC.edit = ^(BOOL editFlag) {
        if (editFlag) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf loadData];
        }
    };
    [self.navigationController pushViewController:CMEVC animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
- (void)okBtnTap {
    okBtn.selected = !okBtn.selected;
    [cTableView setEditing:okBtn.selected animated:YES];
    [okBtn setTitleColor:(okBtn.selected?THEMECOLOR_OF_ORANGE:THEMECOLOR_OF_TEXT_333333) forState:UIControlStateNormal];
    [okBtn setTitle:(okBtn.selected?@"完成":@"排序") forState:UIControlStateNormal];
    addBtn.hidden = okBtn.selected;
    recordSort = !recordSort;
    if (recordSort) {
        [self upDataForSort];
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSLog(@"点击了删除");
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        self->deleteRow = indexPath.row;
        [strongSelf upDataForDelete:indexPath];
    }];
    UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSLog(@"点击了编辑");
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        ChatMessageEditViewController *CMEVC = [[ChatMessageEditViewController alloc] init];
//        ChatSentenceModel *model = self->dataArray[indexPath.row];
        ChatSentenceModel *model = [DataToolsControl sharedManager].chatSentenceArray[indexPath.row];
        CMEVC.editModel = [model copy];
        CMEVC.edit = ^(BOOL editFlag) {
            if (editFlag) {
                __strong __typeof(weakSelf)strongSelf = weakSelf;
                [strongSelf loadData];
            }
        };
        [strongSelf.navigationController pushViewController:CMEVC animated:YES];
    }];
    editAction.backgroundColor = [UIColor grayColor];
    return @[deleteAction, editAction];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    editingStyle = UITableViewCellEditingStyleDelete;
}
#pragma mark 排序 当移动了某一行时候会调用
//编辑状态下，只要实现这个方法，就能实现拖动排序
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
//    [dataArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    [[DataToolsControl sharedManager].chatSentenceArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)upDataForDelete:(NSIndexPath *)indexPath {
    SVPHUDShow;
//    ChatSentenceModel *model = dataArray[indexPath.row];
    ChatSentenceModel *model = [DataToolsControl sharedManager].chatSentenceArray[indexPath.row];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setValue:model.id forKey:@"id"];
    [BaseNetManager requestWithMethod:POST path:Chat_DeleteSentence_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(@"删除成功");
//            [self->dataArray removeObjectAtIndex:self->deleteRow];
            [[DataToolsControl sharedManager].chatSentenceArray removeObjectAtIndex:self->deleteRow];
            [self->cTableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationFor_ChatMessage_Delete_OK object:nil];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)upDataForSort {
    SVPHUDShow;
//    ChatSentenceModel *model = dataArray.firstObject;
//    NSString *ids = model.id;
//    for (NSInteger i = 1; i < dataArray.count; i++) {
//        ChatSentenceModel *tempModel = dataArray[i];
//        ids = [NSString stringWithFormat:@"%@,%@", ids, tempModel.id];
//    }
    ChatSentenceModel *model = [DataToolsControl sharedManager].chatSentenceArray.firstObject;
    NSString *ids = model.id;
    for (NSInteger i = 1; i < [DataToolsControl sharedManager].chatSentenceArray.count; i++) {
        ChatSentenceModel *tempModel = [DataToolsControl sharedManager].chatSentenceArray[i];
        ids = [NSString stringWithFormat:@"%@,%@", ids, tempModel.id];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setValue:ids forKey:@"ids"];
    [BaseNetManager requestWithMethod:POST path:Chat_SortSentence_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(@"成功");
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationFor_ChatMessage_OK object:nil];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)addBtnTap {
    ChatMessageEditViewController *CMEVC = [[ChatMessageEditViewController alloc] init];
    __weak typeof(self) weakSelf = self;
    CMEVC.edit = ^(BOOL editFlag) {
        if (editFlag) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf loadData];
        }
    };
    [self.navigationController pushViewController:CMEVC animated:YES];
}

@end
